package com.example.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.util.Result;
import com.example.common.util.ResultCodeEnum;
import com.example.dto.system.SysUserRoleDto;
import com.example.system.Role;
import com.example.system.SysUserRole;
import com.example.system.mapper.RoleMapper;
import com.example.system.mapper.SysUserRoleMapper;
import com.example.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    /**
     * 分页查询
     * @return
     */
    @Override
    public Result getPageList(int page, int limit, String searchObj) {
        if (page == 0 || page < 0 ) {
            page = 1;
        }
        if(limit == 0 || limit < 0 || limit >20){
            limit = 10;
        }
        Page<Role> ipage = new Page<>(page,limit);
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(searchObj)){
            wrapper.like(Role::getRoleName,searchObj);
        }
        IPage<Role> roleIPage = page(ipage, wrapper);
//        System.out.println(roleIPage.getRecords());
        return Result.ok(roleIPage);
    }


    /**
     * 根据id查询角色信息
     * @param id
     * @return
     */
    @Override
    public Result getById(Long id) {
        if (id.equals(null)){
            return Result.fail();
        }
        Role role = baseMapper.selectById(id);
        return Result.ok(role);
    }

    /**
     * 添加角色信息
     * @param role
     * @return
     */
    @Override
    public Result insert(Role role) {
        //角色名称跟编码不能为空
        if(StringUtils.isBlank(role.getRoleName())||StringUtils.isBlank(role.getRoleCode())){
            return Result.build("添加失败", ResultCodeEnum.DATA_ERROR);
        }
        boolean save = save(role);
        if(!save){
            return Result.fail("添加失败");
        }
        return Result.ok("添加成功");
    }

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 给用户分配角色
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public Result doAssign(SysUserRoleDto dto) {
        if(dto == null){
            return Result.fail();
        }
        Long userId = dto.getUserId();
        //删除该用户的所有角色
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId,userId);
        sysUserRoleMapper.delete(wrapper);

        //给用户添加角色
        List<Long> roleIdList = dto.getRoleIdList();
        for (Long aLong : roleIdList) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(aLong);
            sysUserRoleMapper.insert(sysUserRole);
        }

        return Result.ok();
    }

    /**
     * 根据userid获取角色
     * @param userId
     * @return
     */
    @Transactional
    public Result getRoles(Long userId){
        if(userId == null){
            return Result.fail();
        }
        Map<String,Object> map = new HashMap<>();

        //1 查询所有角色，返回list集合，返回
        List<Role> roles = list();
        map.put("allRolesList",roles);
        //2 根据userid查询 角色用户关系表，查询userid对应所有角色id
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId,userId);
        List<SysUserRole> userRoles = sysUserRoleMapper.selectList(wrapper);
        // 从查询出来的用户id对应角色list集合，获取所有角色id
        List<Long> list = new ArrayList();
        for (SysUserRole userRole : userRoles) {
            list.add(userRole.getRoleId());
        }
        //3 根据查询所有角色id，找到对应角色信息
        //根据角色id到所有的角色的list集合进行比较
        List<Role> assginRoleList = new ArrayList<>();
        for (Role role : roles) {
            if(list.contains(role.getId())){
                assginRoleList.add(role);
            }
        }
        map.put("assginRoleList",assginRoleList);
        return Result.ok(map);
    }


}
